package com.dhcy.mqtt.service.impl;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhcy.mqtt.bean.MenuManageListResult;
import com.dhcy.mqtt.bean.TreeResource;
import com.dhcy.mqtt.dao.*;
import com.dhcy.mqtt.exception.GlobalException;
import com.dhcy.mqtt.model.*;
import com.dhcy.mqtt.par.ht.*;
import com.dhcy.mqtt.result.ht.AuthListResult;
import com.dhcy.mqtt.result.ht.AuthRoleListResult;
import com.dhcy.mqtt.result.ht.TableResultData;
import com.dhcy.mqtt.service.SysUserService;
import com.dhcy.mqtt.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@SuppressWarnings("rawtypes")
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    SysResourceMapper sysResourceMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    SysRoleResourceMapper sysRoleResourceMapper;

    @Value("${BASEIMGPATH}")
    String BASEIMGPATH;
    @Value("${baseStaticUrl}")
    String baseStaticUrl;

    @Value("${PROJECTNAME}")
    private String PROJECTNAME;


    @Override
    public List<SysResource> getResourceListByusername(String username) {
        return sysResourceMapper.getResourceListByusername(username);
    }

    @Override
    public TableResultData authList(AuthListPar authListPar) {
        IPage<SysRole> sele = sysRoleMapper.selectPage(new Page<SysRole>(authListPar.getPage(), authListPar.getPageSize()), null);
        List<SysRole> seleL = sele.getRecords();
        List<AuthListResult> list = new ArrayList<>();
        for (SysRole authRole : seleL) {
            AuthListResult authListResult = new AuthListResult();
            BeanUtils.copyProperties(authRole, authListResult);
            authListResult.setStatusString(StatusUtil.map.get(authRole.getStatus()));
            list.add(authListResult);
        }
        return TableResultData.success(sele.getTotal(), list);
    }

    @Override
    public TableResultData authRoleList(AuthRoleListPar authRoleListPar) {
        IPage page = new Page<>(authRoleListPar.getPage(), authRoleListPar.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!IsNull.isNullOrEmpty(authRoleListPar.getUsername())) {
            queryWrapper.like("su.USERNAME", authRoleListPar.getUsername());
        }
        if (!IsNull.isNullOrEmpty(authRoleListPar.getRealName())) {
            queryWrapper.like("su.REAL_NAME", authRoleListPar.getRealName());
        }
        List<AuthRoleListResult> resultList = baseMapper.getAuthList(page, queryWrapper);
        for (AuthRoleListResult result : resultList) {
            result.setStatusString(StatusUtil.map.get(result.getStatus()));
        }


        return TableResultData.success(page.getTotal(), resultList);
    }

    @Override
    public TableResultData menuManageList(MenuManageListPar menuManageListPar) {
        IPage page = new Page<>(menuManageListPar.getPage(), menuManageListPar.getPageSize());
        List<MenuManageListResult> menuManageList = sysResourceMapper.getMenuManageList(page);

        return TableResultData.success(page.getTotal(), menuManageList);
    }


    @Override
    public AppResultData authRoleTree() {
        List<SysRole> list = sysRoleMapper.selectList(null);
        return AppResultData.success("", list);
    }

    @Override
    public AppResultData UpauthRole(UPauthRolePar upauthRolePar) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("USERNAME", upauthRolePar.getUsername());
        List<SysUser> sele = baseMapper.selectByMap(columnMap);
        if (sele.size() != 0&&IsNull.isNullOrEmpty(upauthRolePar.getId())) {
            throw new GlobalException(AppResultData.errorMessage("管理员姓名已存在"));
        }
        SysUser sysUser = new SysUser();
        if (!IsNull.isNullOrEmpty(upauthRolePar.getId())) {
            sysUser = baseMapper.selectById(upauthRolePar.getId());
            sysUser.setUpdateTime(new Date());
        }
        if (!StringUtils.isEmpty(upauthRolePar.getPassword())) {
            sysUser.setPassword(Md5Util.getHtMd5(upauthRolePar.getPassword()));
        }
        sysUser.setUsername(upauthRolePar.getUsername());
        sysUser.setRealName(upauthRolePar.getRealName());
        if (IsNull.isNullOrEmpty(upauthRolePar.getId())) {
            if (StringUtils.isEmpty(upauthRolePar.getPassword())) {
                return AppResultData.errorMessage("密码不能为空");
            }
            sysUser.setCreateTime(new Date());
            baseMapper.insert(sysUser);
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(upauthRolePar.getRid());
            sysUserRole.setUserId(sysUser.getId());
            sysUserRoleMapper.insert(sysUserRole);
            return AppResultData.successMessage("成功");
        } else {

            UpdateWrapper<SysUser> queryWrapper = new UpdateWrapper<>();
            queryWrapper.eq("ID", upauthRolePar.getId());
            columnMap = new HashMap<>();
            columnMap.put("USER_ID", upauthRolePar.getId());
            List<SysUserRole> a = sysUserRoleMapper.selectByMap(columnMap);
            SysUserRole sysUserRole = a.get(0);
            sysUserRole.setRoleId(upauthRolePar.getRid());
            int number2 = sysUserRoleMapper.updateById(sysUserRole);
            if (number2 > 0) {
                int number = baseMapper.updateById(sysUser);
                if (number > 0) {
                    return AppResultData.successMessage("修改成功");
                }
            }
        }
        throw new GlobalException(AppResultData.errorMessage("管理员编辑错误"));
    }

    @Override
    public AppResultData OFFauthRole(OFFauthRolePar offauthRolePar) {
        SysUser entity = baseMapper.selectById(offauthRolePar.getId());
        entity.setId(offauthRolePar.getId());
        entity.setStatus(offauthRolePar.getStatus());
        int number = baseMapper.updateById(entity);
        if (number == 0) {
            throw new GlobalException(AppResultData.errorMessage("管理员修改状态错误"));
        }
        return AppResultData.successMessage("修改成功");
    }

    @Override
    public AppResultData DELauthRole(DELauthRolePar delauthRolePar) {
        UpdateWrapper<SysUserRole> queryWrapper = new UpdateWrapper<>();
        queryWrapper.eq("USER_ID", delauthRolePar.getId());
        sysUserRoleMapper.delete(queryWrapper);
        int number = baseMapper.deleteById(delauthRolePar.getId());
        if (number == 0) {
            throw new GlobalException(AppResultData.errorMessage("管理员删除错误"));
        }
        return AppResultData.successMessage("删除成功");
    }

    @Override
    public AppResultData delRole(DelRolePar delRolePar) {
        SysRole a = sysRoleMapper.selectById(delRolePar.getId());
        QueryWrapper<SysRoleResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ROLE_ID", a.getRoleId());
        sysRoleResourceMapper.delete(queryWrapper);
        int num = sysRoleMapper.deleteById(delRolePar.getId());
        if (num == 0) {
            throw new GlobalException(AppResultData.errorMessage("删除角色异常"));
        } else {
            return AppResultData.successMessage("删除成功");
        }
    }

    @Override
    public AppResultData setRole(SetRolePar setRolePar) {
        String[] strs = setRolePar.getStr().split(",");
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("ROLE_ID", setRolePar.getRoleId());
        sysRoleResourceMapper.deleteByMap(columnMap);
        for (String string : strs) {
            SysRoleResource entity = new SysRoleResource();
            entity.setRoleId(setRolePar.getRoleId());
            entity.setResourceCode(string);
            sysRoleResourceMapper.insert(entity);
        }
        return AppResultData.successMessage("修改成功");
    }

    @Override
    public AppResultData upRole(UpRolePar upRolePar) {
        SysRole sysRole = sysRoleMapper.selectById(upRolePar.getId());
        if (IsNull.isNullOrEmpty(sysRole)) {
            throw new GlobalException(AppResultData.errorMessage("编辑角色异常"));
        } else {
            sysRole.setUpdateTime(DateUtil.timeStamp());
            sysRole.setRoleName(upRolePar.getRoleName());
            sysRole.setRoleIntro(upRolePar.getRoleIntro());
            sysRole.setStatus(upRolePar.getStatus());
            int number = sysRoleMapper.updateById(sysRole);
            if (number == 0) {
                throw new GlobalException(AppResultData.errorMessage("编辑角色异常"));
            } else {
                return AppResultData.successMessage("编辑成功");
            }
        }

    }

    @Override
    public AppResultData UPMenu(UPMenuPar uPMenuPar) {
        SysResource sysResource = sysResourceMapper.selectById(uPMenuPar.getId());
        sysResource.setResuorceName(uPMenuPar.getName());
        sysResource.setSort(uPMenuPar.getSort());
        int number = sysResourceMapper.updateById(sysResource);
        if (number == 0) {
            throw new GlobalException(AppResultData.errorMessage("修改菜单信息"));
        } else {
            return AppResultData.successMessage("修改成功");
        }
    }


    @Override
    public AppResultData addRole(AddRolePar addRolePar) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(addRolePar, sysRole);
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        if (IsNull.isNullOrEmpty(addRolePar.getId())) {
            //生成一个永不重复的id
            sysRole.setRoleId(IdUtil.objectId());
            sysRole.setCreateTime(DateUtil.timeStamp());
            sysRole.setCreater(username);
            sysRoleMapper.insert(sysRole);
        } else {
            sysRole.setUpdateTime(DateUtil.timeStamp());
            sysRole.setUpdator(username);
            sysRoleMapper.updateById(sysRole);
            sysRole = sysRoleMapper.selectById(sysRole.getId());
            QueryWrapper<SysRoleResource> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ROLE_ID", sysRole.getRoleId());
            sysRoleResourceMapper.delete(queryWrapper);
        }
        String[] str = addRolePar.getStr().split(",");
        for (String string : str) {
            SysRoleResource entity1 = new SysRoleResource();
            entity1.setRoleId(sysRole.getRoleId());
            entity1.setResourceCode(string);
            sysRoleResourceMapper.insert(entity1);
        }
        return AppResultData.successMessage("成功");
    }


    @Override
    public AppResultData ADDauthRole(ADDauthRolePar addauthRolePar) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("USERNAME", addauthRolePar.getUsername());
        List<SysUser> sele = baseMapper.selectByMap(columnMap);
        if (sele.size() != 0) {
            return AppResultData.errorMessage("管理员名字已存在");
        }
        SysUser entity = new SysUser();
        entity.setCreateTime(new Date());
        entity.setPassword(Md5Util.getHtMd5(addauthRolePar.getPassword()));
        entity.setUsername(addauthRolePar.getUsername());
        entity.setUpdateTime(new Date());
        entity.setRealName(addauthRolePar.getRealName());
        int number = baseMapper.insert(entity);
        if (number == 0) {
            throw new GlobalException(AppResultData.errorMessage("添加失败"));
        } else {
            Map<String, Object> columnMap1 = new HashMap<>();
            columnMap1.put("USERNAME", addauthRolePar.getUsername());
            List<SysUser> a = baseMapper.selectByMap(columnMap1);
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("USER_ID", a.get(0).getId());
            SysUserRole entity1 = new SysUserRole();
            entity1.setUserId(a.get(0).getId());
            entity1.setRoleId(addauthRolePar.getRid());
            int num = sysUserRoleMapper.insert(entity1);
            if (num == 0) {
                throw new GlobalException(AppResultData.errorMessage("添加失败"));
            } else {
                return AppResultData.successMessage("添加成功");
            }
        }
    }

    @Override
    public List<TreeResource> getTreeResourceListByusername(String id) {
        List<TreeResource> sysResourceList = sysResourceMapper.getTreeResourceListById(id);
        Map<Integer, TreeResource> map = new LinkedHashMap<>();
        Map<Integer, TreeResource> map1 = new LinkedHashMap<>();
        for (TreeResource treeResource : sysResourceList) {
            if (!IsNull.isNullOrEmpty(treeResource.getId())) {
                treeResource.setChecked(true);
            }
            if (treeResource.getParentId() == null) {
                treeResource.setData(new ArrayList<>());
                map.put(treeResource.getSid(), treeResource);
            } else {
                if (treeResource.getType() == 1) {
                    TreeResource treeResource1 = map.get(treeResource.getParentId());
                    if (treeResource1 != null) {
                        treeResource.setData(new ArrayList<>());
                        map1.put(treeResource.getSid(), treeResource);
                        List<TreeResource> treeResourceList = treeResource1.getData();
                        treeResourceList.add(treeResource);
                    }
                } else {
                    TreeResource treeResource2 = map1.get(treeResource.getParentId());
                    if (treeResource2 != null) {
                        List<TreeResource> treeResourceList = treeResource2.getData();
                        treeResourceList.add(treeResource);
                    }
                }
            }
        }
        List<TreeResource> treeResourceList = new ArrayList<>();
        for (Integer key : map.keySet()) {
            TreeResource treeResource = map.get(key);
            formatTreeResource(treeResource);
            treeResourceList.add(treeResource);
        }
        return treeResourceList;
    }


    @Override
    public AppResultData AddMenuTree() {
        List<SysResource> list = sysResourceMapper.selectList(null);
        return AppResultData.success("", list);
    }

    private void formatTreeResource(TreeResource treeResource) {
        if (treeResource != null) {
            treeResource.setSid(null);
            treeResource.setId(null);
            treeResource.setParentId(null);
            treeResource.setType(null);
            List<TreeResource> dataList = treeResource.getData();
            if (dataList != null) {
                for (TreeResource treeResource1 : dataList) {
                    formatTreeResource(treeResource1);
                }
            }
        }
    }


    @Override
    public Object controller(HttpServletRequest httpServletRequest, String action) {
        if (httpServletRequest instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) httpServletRequest;
            Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
            for (String key : fileMap.keySet()) {

            }
        }
        switch (action) {
            case "config":
                Map<String, Object> map = new HashMap<>();
                // map.put("imageActionName",baseUrl+"sysUser/upims.json");
                map.put("imageActionName", "uploadimage");
                map.put("imageFieldName", "upfile");
                map.put("imageMaxSize", 2048000);
                String[] types = new String[]{".png", ".jpg", ".jpeg", ".gif", ".bmp"};
                map.put("imageUrlPrefix", baseStaticUrl);
                map.put("imageAllowFiles", types);
                map.put("scrawlActionName", "uploadimage");
                map.put("scrawlFieldName", "upfile");
                map.put("scrawlMaxSize", 2048000);
                map.put("scrawlUrlPrefix", baseStaticUrl);
                map.put("snapscreenActionName", "uploadimage");
                map.put("snapscreenUrlPrefix", baseStaticUrl);
                //上传视频格式
                map.put("videoActionName", "uploadimage");
                map.put("videoFieldName", "upfile");
                map.put("videoMaxSize", 102400000);
                String[] videotypes = new String[]{
                        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav"};
                map.put("videoUrlPrefix", baseStaticUrl);
                map.put("videoAllowFiles", videotypes);
                //上传文件
                map.put("fileActionName", "uploadimage");
                map.put("fileFieldName", "upfile");
                map.put("fileMaxSize ", 51200000);
                String[] filetypes = new String[]{
                        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
                        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
                        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
                        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"};
                map.put("fileUrlPrefix", baseStaticUrl);
                map.put("fileAllowFiles", filetypes);

                map.put("imageManagerActionName", "listimage");
                map.put("imageManagerUrlPrefix", baseStaticUrl);
                map.put("imageManagerListSize ", 20);

                map.put("fileManagerActionName", "listfile");
                map.put("fileManagerUrlPrefix", baseStaticUrl);
                map.put("fileManagerListSize", 20);
                return map;
            case "uploadimage":
                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) httpServletRequest;
                MultipartFile upfile = multipartHttpServletRequest.getFile("upfile");
                return ueditorUpimg(upfile, "ueditor");
            case "listimage":
                Map<String, Object> maps = new HashMap<>();
                File file = new File(BASEIMGPATH + "ueditor");
                File[] files = file.listFiles(new ImageFilter());
                int start = Integer.parseInt(httpServletRequest.getParameter("start"));
                List<Map<String, String>> imglist = new ArrayList<>();
                assert files != null;
                for (int i = start; i < files.length; i++) {
                    Map<String, String> imgMap = new HashMap<>();
                    imgMap.put("url", "/" + PROJECTNAME + "/ueditor/" + files[i].getName());
                    imglist.add(imgMap);
                }
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("state", "SUCCESS");
                resultMap.put("list", imglist);
                resultMap.put("start", start);
                resultMap.put("total", files.length);
                return resultMap;
        }
        return null;
    }

    public UeditorResult ueditorUpimg(MultipartFile file, String foldName) {
        PicUpresult picUpresult = upimgs(file, foldName);
        UeditorResult ueditorResult = new UeditorResult();
        ueditorResult.setState("SUCCESS");
        ueditorResult.setUrl("/" + picUpresult.getSrc());
        ueditorResult.setTitle(picUpresult.getFilename());
        ueditorResult.setOriginal(picUpresult.getFilename());
        return ueditorResult;
    }

    @Override
    public PicUpresult upimgs(MultipartFile file, String foldName) {
        String hashName = Md5Util.md5HashCode32(file);
        if (StringUtils.isEmpty(hashName)) {
            hashName = (System.currentTimeMillis() + "").substring(8) + "" + RandomUtil.getNumberCode(6);
        }
        //String filename = (System.currentTimeMillis() + "").substring(8);
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String filename = hashName + suffix;
        String url = BASEIMGPATH + foldName + "/";
        try {
            File folder = new File(url);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
            }
            File file1 = new File(url + filename.trim());
            if (!file1.exists())
                file1.createNewFile();
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PicUpresult picUpresult = new PicUpresult();
        url = "/" + PROJECTNAME + "/" + foldName + "/" + filename;
        picUpresult.setFilename(filename);
        picUpresult.setSrc(url);
        return picUpresult;
    }

    @Override
    public AppResultData modifyHtPass(String oldPass, String newPass) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USERNAME", username);
        List<SysUser> users = baseMapper.selectList(queryWrapper);
        if (users.size() == 0)
            throw new GlobalException(AppResultData.errorMessage("请先登录"));
        SysUser sysUser = users.get(0);
        String realOldPass = Md5Util.getHtMd5(oldPass);
        if (!realOldPass.equals(sysUser.getPassword())) {
            throw new GlobalException(AppResultData.errorMessage("原密码错误"));
        }
        sysUser.setPassword(Md5Util.getHtMd5(newPass));
        sysUser.setUpdateTime(new Date());
        baseMapper.updateById(sysUser);
        SecurityUtils.getSubject().logout();
        return AppResultData.successMessage("修改成功");
    }

     public  AppResultData getTopMenuList(){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.isNull("parent_id");
         List list = sysResourceMapper.selectList(queryWrapper);
         return  AppResultData.success("成功",list);
     }

}
